package com.doys.myfirstapp;
import android.Manifest;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.*;
import android.widget.ProgressBar;

import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;
import com.U8.UHFApplication;
import com.U8.model.Message;
import com.U8.operation.IUSeries;
import com.U8.reader.model.InventoryBuffer;
import com.U8.reader.server.ReaderHelper;
import com.U8.utils.MusicPlayer;
import com.doys.myfirstapp.u8.ConcentratedSettingFragment;
import com.doys.myfirstapp.u8.InventoryFragment;
import com.doys.myfirstapp.u8.ReadAndWriteFragment;
import com.doys.myfirstapp.u8.U8Series2;

import java.io.File;

public class ActivityBroadcast extends FragmentActivity implements ScanCodeBroadcastReceiver.OnReceiveCode {
    private boolean isInput;
    public static WebView webView;
    ProgressBar pb1;
    ScanCodeBroadcastReceiver receiver;

    private ValueCallback<Uri> mUploadFile;


    //U8
    private static String model = "U8";
    private String packageName = "com.fn.useries.u8";
    private String activityName = "com.fn.useries.activity.MainActivity";
    private boolean isJumpExit;

    private static InventoryBuffer m_curInventoryBuffer = null;

    private ReadAndWriteFragment rwFragment = null;
    private InventoryFragment inventoryFragment = null;
    private ConcentratedSettingFragment concentratedSettingFragment;
    public static IUSeries mUSeries;
    private PendingIntent mPermissionIntent;
    public static final String ACTION_DEVICE_PERMISSION = "com.linc.USB_PERMISSION";
    //    String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA};

    public static void powerOn() {
        ActivityBroadcast.mUSeries.modulePowerOn(model); //上电

        ActivityBroadcast.mUSeries.openSerialPort(model);   //打开串口


    }

    @Override
    protected void onResume() {
        ActivityBroadcast.powerOn();
        super.onResume();
    }


    // -- Activity events -----------------------------------------------------
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogToFile.i("test","test");
        setContentView(R.layout.activity_main);

        initWebView();
        loadUrl("");

        initBroadcastReceiver();
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        JSInterface.soundUtils = new SoundUtils(this, SoundUtils.RING_SOUND);
        JSInterface.soundUtils.putSound(0, R.raw.scan_ok);
        JSInterface.soundUtils.putSound(1, R.raw.scan_error);
        JSInterface.soundUtils.putSound(2, R.raw.msg);

        UHFApplication.applicationContext = this;
        U8Series2.setContext(this);
        mUSeries = U8Series2.getInstance();
        boolean flag = true;
        if (Build.VERSION.SDK_INT >= 23) {  //安卓系统6.0以上危险权限需要动态权限申请
            //验证是否许可权限
            int REQUEST_CODE_CONTACT = 101;
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    flag = false;
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);    //申请权限
                }
            }
        }
        if (flag) {
            operte();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {   //申请权限回调
        boolean flag = false;
        if (permissions.length == 0) {
            return;
        }
        for (int perm : grantResults) {
            if (perm == 0) {
                flag = true;
            } else {
                finish();
                return;
            }
        }
        if (flag) {
            mUSeries.modulePowerOn(model);
            operte();
        }
    }

    /**
     * 模块下电，关闭串口
     */
    public static void EndWork() {
        try {
            ActivityBroadcast.mUSeries.stopInventory();
        } catch (Exception e) {
            e.printStackTrace();
        }

        ActivityBroadcast.mUSeries.modulePowerOff(model);  //下电
        ActivityBroadcast.mUSeries.closeSerialPort();    //关闭串口

        MusicPlayer.getInstance().play(MusicPlayer.Type.OK);
    }

    public void operte() {
        try {
            ReaderHelper.setContext(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            m_curInventoryBuffer = ReaderHelper.getDefaultHelper().getCurInventoryBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);

        if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webView.clearHistory();

            ((ViewGroup) webView.getParent()).removeView(webView);
            webView.destroy();
            webView = null;
        }
        super.onDestroy();

        if (!isJumpExit) {
            EndWork(); // 下电，关闭串口
        }
    }
    // -- WebView Process ----------------------------------------------------- s
    private void initWebView() {
        webView = findViewById(R.id.webView1);
        pb1 = findViewById(R.id.progressBar1);

        WebSettings webSettings = webView.getSettings();

        webSettings.setJavaScriptEnabled(true);                         // -- 支持Javascript交互 --
        webSettings.setDefaultTextEncodingName("utf-8");                // -- 设置编码格式 --
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);     // -- 支持通过JS弹出对话框 --
        webSettings.setAllowFileAccess(true);

        // -- 使支持localStorage --
        webSettings.setDomStorageEnabled(true);
        //webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        //String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        //webSettings.setAppCachePath(appCachePath);
        //webSettings.setAllowFileAccess(true);
        //webSettings.setAppCacheEnabled(true);

        //给webview添加JavaScript接口
        JSInterface.context = getApplicationContext();
        JSInterface.activity = this;
        webView.addJavascriptInterface(new JSInterface(), "callAndroid");


        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // -- 打开网页时不调用系统浏览器 --
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress < 100) {
                    pb1.setVisibility(View.VISIBLE);
                    pb1.setProgress(newProgress);
                }
                else if (newProgress == 100) {
                    pb1.setVisibility(View.GONE);
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                new AlertDialog.Builder(ActivityBroadcast.this)
                        .setTitle("系统信息...")
                        .setMessage(message)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.confirm();
                            }
                        })
                        .setCancelable(false)
                        .show();
                return true;
            }
            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                new AlertDialog.Builder(ActivityBroadcast.this)
                        .setTitle("系统信息...")
                        .setMessage(message)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.confirm();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.cancel();
                            }
                        })
                        .setCancelable(false)
                        .show();
                return true;
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                WebCameraHelper.getInstance().mUploadMessage = uploadMsg;
                WebCameraHelper.getInstance().showOptions(ActivityBroadcast.this);
            }

            // For Android > 4.1.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                        String acceptType, String capture) {
                WebCameraHelper.getInstance().mUploadMessage = uploadMsg;
                WebCameraHelper.getInstance().showOptions(ActivityBroadcast.this);
            }

            // For Android > 5.0支持多张上传
            @Override
            public boolean onShowFileChooser(WebView webView,
                                             ValueCallback<Uri[]> uploadMsg,
                                             FileChooserParams fileChooserParams) {
                WebCameraHelper.getInstance().mUploadCallbackAboveL = uploadMsg;
                WebCameraHelper.getInstance().showOptions(ActivityBroadcast.this);
                return true;
            }
        });
        pb1.setVisibility(View.GONE);
        pb1.setMax(100);
    }

    public static void loadUrl(String urlDefault) {
        //webView.loadUrl("http://192.168.2.66/DoYsUI/index.html");
        //webView.loadUrl("http://127.0.0.1/DoYsUI/index.html");
        //webView.loadUrl("http://www.baidu.com/");
        //webView.loadUrl("http://192.168.2.66:5556");
        //webView.loadUrl("http://192.168.2.66:7000/xpas/project/g_spd/html/pda/dist/mobile.html#/login");

        //webView.loadUrl("http://192.168.2.66:7000/xpas/project/g_spd/html/app_login.html");

        webView.loadUrl("file:///android_asset/index.html");
    }

    // -- do scan -------------------------------------------------------------
    private void initBroadcastReceiver() {
        receiver = new ScanCodeBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        //intentFilter.addAction("com.android.scanservice.scancontext");
        //intentFilter.addAction("a");
        intentFilter.addAction("com.android.server.scannerservice.broadcast");
        intentFilter.addAction("android.provider.sdlMessage");

        registerReceiver(receiver, intentFilter);

        receiver.setOnReceive(this);
    }
    @Override
    public void notifyScan(String Code) {
        System.out.println("Code111111111111"+Code);
        //MessageBox.getInfoBuilder(this, Code).show();
        try {
            webView.loadUrl("javascript:androidCallJS({\"code\": \"" + Code + "\"})");
        } catch (Exception e) {
//            MessageBox.getInfoBuilder(this, e.getMessage()).show();
        }
    }


    /**
    * @Description： 推送rfid单个扫描结果
    * @Author wyt
    * @Date 2021/4/26
    */
    public static void rfidScanMsgPush(String msg) {
        try {
            webView.loadUrl("javascript:rfidScanMsgGet({\"msg\": \"" + msg + "\"})");
        } catch (Exception e) {
            e.printStackTrace();
//            MessageBox.getInfoBuilder(this, e.getMessage()).show();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case 137:
                Toast.makeText(JSInterface.context,"onKeyDown",Toast.LENGTH_SHORT).show();
                if (inventoryFragment instanceof InventoryFragment) {
                    ((InventoryFragment) inventoryFragment).onKeyDown(keyCode, event);
                    return true;
                }
                break;
        }
        if (keyCode== KeyEvent.KEYCODE_BACK) {//返回键
            // 没有返回值
//            webView.loadUrl("javascript:androidBack()");

            // 有返回值
            webView.evaluateJavascript("androidBack("+ keyCode +")", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    // 手动返回
                    if (!value.equals("false")) {
                        onBackPressed();
                    }

                }
            });
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
//            case 137:
//                Toast.makeText(JSInterface.context,"onKeyUp",Toast.LENGTH_SHORT).show();
//                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (InventoryFragment.isInventory) {
            try {
                if (!mUSeries.stopInventory()) {
                    Toast.makeText(ActivityBroadcast.this, "停止盘询失败", Toast.LENGTH_SHORT).show();
                }
                mUSeries.modulePowerOff(model); //下电
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x03;
    private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0x04;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    private Uri imageUri;
    private Uri cropImageUri;

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    private int output_X = 480;
    private int output_Y = 480;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        WebCameraHelper.getInstance().onActivityResult(requestCode, resultCode, data);
    }
}
